package com.cncf.controller.manage;

import com.cncf.entity.InvalidReportFile;
import com.cncf.response.ResponseData;
import com.cncf.service.InvalidReportFileService;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * @author zj
 */
@Api(value = "Manage", description = "管理检验报告原件作废信息的相关接口")
@Controller
@RequestMapping("/manage/invalidReportFile")
public class ManageInvalidReportFileController {
    private static final Logger logger = LoggerFactory.getLogger(ManageInvalidReportFileController.class);

    @Autowired
    private InvalidReportFileService invalidReportFileService;

    @ApiOperation(value = "解析服务器中的作废的报告原件excel", notes = "解析之前要先将excel文件上传到服务器")
    @RequestMapping(value = "importInvalidReportExcel", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData<Boolean> importInvalidReportExcel(
            @ApiParam("excel作废报告文件url") @RequestParam("url") String url) throws IOException {

        ResponseData<Boolean> responseData = new ResponseData<>();
        File file = new File(url);
        String name = file.getName();
        long length = file.length();
        //String name = url.substring(url.lastIndexOf("/") + 1);// 从全路径中提取文件名
        //也许不会出现一下几种情况但是多判断一下有备无患
        if (name == null || "".equals(name) || length == 0) {
            return null;
        }

        InputStream in = new FileInputStream(file);
        boolean res = invalidReportFileService.insertInvalidReportForBatch(name, in);
        if (!res) {
            responseData.jsonFill(2, "插入失败（插入数据库的记录数不等于表格中的记录数）", false);
            return responseData;
        }
        responseData.jsonFill(1, null, true);
        return responseData;
    }

    @ApiOperation(value = "获取所有的检验报告原件作废信息", notes = "不提供page和pageSize就不分页")
    @RequestMapping(value = "getAllInvalidReportFile", method = {RequestMethod.GET})
    @ResponseBody
    public ResponseData<List<InvalidReportFile>> getAllInvalidReportFile(
            @ApiParam("page") @RequestParam(value = "page", required = false) Integer page,
            @ApiParam("pageSize") @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        ResponseData<List<InvalidReportFile>> responseData = new ResponseData<>();
        List<InvalidReportFile> list = invalidReportFileService.getAllInvalidReportFile(page, pageSize);
        responseData.jsonFill(1, null, list);
        responseData.setCount(list.size());
        return responseData;
    }

}
